package com.yu.yupicture.manger.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yu.yupicture.config.cosConfig;
import com.yu.yupicture.exception.ErrorCode;
import com.yu.yupicture.exception.biusnessException;
import com.yu.yupicture.model.domain.dto.picture.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;


@Slf4j
public abstract class CommenUpliadUntil {

    @Resource
    private CosUntil cosUntil;
    @Resource
    private cosConfig cosConfig;

    /**
     * 上传并校验文件
     */

    public UploadPictureResult uploadFile(String pathPrev, Object input)
            throws CosClientException, CosServiceException {
        //1：校验文件
        validateFile(input);
        //2 获取原始文件名
        String originalName = getFileName(input);
        //生成文件名 (日期+UUID+文件后缀名)
        String fileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), UUID.randomUUID(false), FileUtil.getSuffix(originalName)==null?"jpg":FileUtil.getSuffix(originalName));
        log.info("文件名后缀：{}",FileUtil.getSuffix(originalName));
        //设置文件路径
        String path = String.format("%s/%s", pathPrev, fileName);
        log.info("文件路径 path："+path);

        //上传文件
        File file = null;
        try {
            file = File.createTempFile(path, null);
            //3 处理文件来源
            createTempFile(input, file);
            PutObjectResult putObjectResult = cosUntil.putPictureObject(path, file);

            //获取文件信息
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();


            //获取处理后的图片信息
            List<CIObject> objectList = putObjectResult.getCiUploadResult().getProcessResults().getObjectList();
            if (CollUtil.isNotEmpty(objectList)){
                CIObject ciObject = objectList.get(0);
                CIObject thumbnail=ciObject;
                if (objectList.size()>1){
                    thumbnail= objectList.get(1);
                }

                return getPictureResult(ciObject, originalName, thumbnail, imageInfo,path);
            }
            return getPictureResult(imageInfo, path, originalName, file);

        } catch (IOException e) {
            log.error("file upload error", e);
            throw new biusnessException(ErrorCode.OPERATION_ERROR, "文件上传失败");
        } finally {
            // 删除临时文件
            deleteTempFile(file);
            log.info("file upload end");
        }
    }

    //校验文件
    public abstract void validateFile(Object input);

    //获取文件原始名
    public abstract String getFileName(Object input);

    //处理文件来源
    public abstract void createTempFile(Object input, File file);

    /**
     * 获取处理后的图片信息
     *
     * @param ciObject
     * @param originalName
     * @param thumbnail
     * @param imageInfo
     * @param path
     * @return
     */
    private UploadPictureResult getPictureResult(CIObject ciObject, String originalName, CIObject thumbnail, ImageInfo imageInfo, String path) {

        int width = ciObject.getWidth();
        int height = ciObject.getHeight();
        //宽高比(保留两位小数)
        double scale = NumberUtil.round(width * 1.0, height).doubleValue();

        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosConfig.getHost() + "/" + path);
        uploadPictureResult.setPicName(FileUtil.mainName(originalName));
        uploadPictureResult.setPicSize(ciObject.getSize().longValue());
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(ciObject.getFormat());
        uploadPictureResult.setThumbnailUrl(cosConfig.getHost() + "/" + thumbnail.getKey());


        //获取图片主色调
        uploadPictureResult.setPicColor(imageInfo.getAve());
        return uploadPictureResult;
    }

    /**
     * 获取文件信息
     */
    private UploadPictureResult getPictureResult(ImageInfo imageInfo, String path, String mainName, File file) {
        int width = imageInfo.getWidth();
        int height = imageInfo.getHeight();
        //宽高比(保留两位小数)
        double scale = NumberUtil.round(width * 1.0, height).doubleValue();

        UploadPictureResult uploadPictureResult = new UploadPictureResult();
        uploadPictureResult.setUrl(cosConfig.getHost() + "/" + path);
        uploadPictureResult.setPicName(mainName);
        uploadPictureResult.setPicSize(FileUtil.size(file));
        uploadPictureResult.setPicWidth(width);
        uploadPictureResult.setPicHeight(height);
        uploadPictureResult.setPicScale(scale);
        uploadPictureResult.setPicFormat(imageInfo.getFormat());
        //获取图片主色调
        uploadPictureResult.setPicColor(imageInfo.getAve());
        return uploadPictureResult;
    }

    //删除临时文件
    private void deleteTempFile(File file) {
        if (file != null) {
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error");
            }
        }
    }


}
